<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="'与 ' + ${receiverName} + ' 的聊天'">聊天页面</title>
    <!-- 引入 layui.css -->
    <link rel="stylesheet" href="/layui/css/layui.css">
    <style>
        /* 主容器样式 */
        .chat-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
            background-color: #f2f2f2;
        }

        /* 聊天头部 */
        .chat-header {
            background-color: #393D49;
            color: white;
            padding: 15px;
            font-size: 16px;
            font-weight: bold;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        /* 聊天主体 */
        .chat-body {
            flex: 1;
            overflow-y: auto;
            padding: 15px;
            background-color: white;
        }

        /* 聊天底部 */
        .chat-footer {
            background-color: white;
            padding: 15px;
            border-top: 1px solid #eee;
            position: relative;
        }

        /* 消息项 */
        .message-item {
            margin-bottom: 15px;
            display: flex;
            position: relative;
        }

        /* 左侧消息（接收的消息） */
        .message-left {
            justify-content: flex-start;
        }

        /* 右侧消息（发送的消息） */
        .message-right {
            justify-content: flex-end;
        }

        /* 消息头像 */
        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }

        .message-left .message-avatar {
            margin-right: 10px;
            background-color: #FF5722;
        }

        .message-right .message-avatar {
            margin-left: 10px;
            background-color: #1E9FFF;
            order: 1;
        }

        /* 消息内容容器 */
        .message-content-wrapper {
            max-width: 70%;
        }

        .message-right .message-content-wrapper {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
        }

        /* 消息信息（发送者、时间） */
        .message-info {
            font-size: 12px;
            color: #999;
            margin-bottom: 5px;
        }

        /* 消息内容 */
        .message-content {
            position: relative;
            padding: 10px 15px;
            border-radius: 4px;
            background-color: #f8f8f8;
            word-break: break-word;
            cursor: pointer;
        }

        .message-right .message-content {
            background-color: #1E9FFF;
            color: white;
        }

        /* 消息状态（已读/未读） */
        .message-status {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
            text-align: right;
        }

        /* 消息操作菜单 */
        .message-actions {
            display: none;
            position: absolute;
            right: 0;
            top: 100%;
            background-color: rgba(118, 116, 128, 0.9);
            border-radius: 4px;
            z-index: 100;
            padding: 5px 0;
            min-width: 80px;
        }

        .message-action-item {
            padding: 5px 15px;
            cursor: pointer;
            white-space: nowrap;
            color: white;
        }

        .message-action-item:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }

        .show-actions .message-actions {
            display: block;
        }

        /* 输入框区域 */
        .layui-textarea {
            min-height: 100px;
            resize: none;
            padding-right: 80px;
        }

        /* 发送按钮容器 */
        .send-button-container {
            position: absolute;
            right: 15px;
            bottom: 15px;
            display: flex;
            gap: 10px;
        }

        /* 发送中指示器 */
        .sending-indicator {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.1);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            display: none;
        }

        /* 空聊天提示 */
        .empty-chat {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            color: #999;
            flex-direction: column;
        }

        /* 返回按钮 */
        .back-btn {
            color: white;
            cursor: pointer;
        }

        /* 新增样式 - 消息操作菜单 */
        .message-actions {
            display: none;
            position: absolute;
            right: 0;
            top: 100%;
            background-color: rgba(118, 116, 128, 0.51);
            border-radius: 4px;
            z-index: 100;
            padding: 5px 0;
        }

        .message-action-item {
            padding: 5px 15px;
            cursor: pointer;
            white-space: nowrap;
            color: white;
        }

        .message-action-item:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }

        .show-actions .message-actions {
            display: block;
        }

        .message-content {
            position: relative;
            cursor: pointer;
        }

        /* 已撤回消息样式 */
        .recalled-message {
            color: #999;
            font-style: italic;
        }
    </style>
</head>
<body>
<div class="chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
            <span class="back-btn" onclick="window.history.back()">
                <i class="layui-icon layui-icon-left"></i> 返回
            </span>
        <span th:text="'与 ' + ${receiverName} + ' 的聊天'"></span>
        <span></span> <!-- 占位 -->
    </div>

    <!-- 聊天主体 -->
    <div class="chat-body" id="chatBody">
        <div class="empty-chat" th:if="${#lists.isEmpty(messages)}">
            <i class="layui-icon layui-icon-face-smile" style="font-size: 50px;"></i>
            <p>开始与 [[${receiverName}]] 聊天</p>
        </div>

        <!-- 消息列表 -->
        <div th:each="message : ${messages}" class="message-item clearfix"
             th:classappend="${message.messageObject.sender.id == senderId} ? 'message-right' : 'message-left'"
             th:attr="data-message-id=${message.id}">
            <div class="message-avatar"
                 th:text="${message.messageObject.sender.info.username.substring(0,1)}"
                 th:style="'background-color:' + (${message.messageObject.sender.id == senderId} ? '#1E9FFF' : '#FF5722')"></div>
            <div class="message-content-wrapper">
                <div class="message-info">
                    <span th:text="${message.messageObject.sender.info.username}"></span>
                    <span th:text="${#temporals.format(message.sendTime, 'yyyy-MM-dd HH:mm:ss')}"></span>
                </div>
                <div class="message-content"
                     th:text="${message.content}"
                     th:classappend="${message.content == null} ? 'recalled-message' : ''"
                     th:attr="onclick=${message.messageObject.sender.id == senderId} ? 'showMessageActions(this, event)' : ''">
                    <span th:if="${message.content == null}">消息已撤回</span>
                </div>
                <div class="message-actions">
                    <div class="message-action-item" th:onclick="'recallMessage(' + ${message.id} + ', event)'">撤回</div>
                </div>
                <div class="message-status" th:if="${message.messageObject.sender.id == senderId}">
                    <span th:text="${message.isRead} ? '已读' : '未读'"></span>
                </div>
            </div>
        </div>
    </div>

    <!-- 聊天底部 -->
    <div class="chat-footer">
        <div class="layui-form layui-form-pane">
            <div class="layui-form-item layui-form-text">
                <div class="layui-input-block">
                    <textarea id="messageContent" placeholder="请输入消息内容" class="layui-textarea"></textarea>
                    <div class="send-button-container">
                        <button class="layui-btn" id="sendBtn">发送</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 发送中指示器 -->
<div class="sending-indicator" id="sendingIndicator">
    <div class="layui-anim layui-anim-rotate layui-anim-loop">
        <i class="layui-icon layui-icon-loading" style="font-size: 30px; color: #1E9FFF;"></i>
    </div>
</div>

<!-- 引入 layui.js -->
<script src="/layui/layui.js"></script>
<script>
    layui.use(['jquery', 'layer'], function(){
        var $ = layui.jquery;
        var layer = layui.layer;

        // 当前用户ID和接收者ID
        const currentUserId = [[${senderId}]];
        const currentReceiverId = [[${receiverId}]];
        const currentReceiverName = "[[${receiverName}]]";
        const messageObjectID=[[${messageObjectID}]]

        // 页面加载时滚动到底部
        $(document).ready(function() {
            scrollToBottom();

            // 标记所有未读消息为已读
            markMessagesAsRead();

            // 发送消息按钮点击事件
            $('#sendBtn').click(sendMessage);

            // 输入框回车发送消息
            $('#messageContent').keypress(function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });

            // 点击其他地方隐藏操作菜单
            $(document).click(function(e) {
                if (!$(e.target).closest('.message-content').length) {
                    $('.message-content').removeClass('show-actions');
                }
            });
        });

        // 显示消息操作菜单
        window.showMessageActions = function(element, event) {
            event.preventDefault();
            event.stopPropagation();

            // 隐藏其他操作菜单
            $('.message-content').removeClass('show-actions');

            // 显示当前操作菜单
            $(element).addClass('show-actions');

            return false;
        };

        // 撤回消息
        window.recallMessage = function(messageId, event) {
            if (event) {
                event.stopPropagation();
                event.preventDefault();
            }

            layer.confirm('确定要撤回这条消息吗？', {
                btn: ['确定', '取消'],
                title: '撤回消息'
            }, function() {
                // 显示加载中状态
                const index = layer.load(1, {shade: [0.1, '#fff']});

                $.ajax({
                    url: '/api/messages/recall/' + messageId,
                    type: 'POST',
                    success: function() {
                        layer.close(index);

                        // 直接移除消息元素
                        $(`[data-message-id="${messageId}"]`).remove();

                        layer.msg('撤回成功', {
                            icon: 1,
                            time: 1500,
                            shade: 0.3
                        });

                        // 如果聊天区域空了，显示空状态提示
                        if ($('#chatBody .message-item').length === 0) {
                            $('#chatBody').html(`
                                <div class="empty-chat">
                                    <i class="layui-icon layui-icon-face-smile" style="font-size: 50px;"></i>
                                    <p>开始与 ${currentReceiverName} 聊天</p>
                                </div>
                            `);
                        }
                    },
                    error: function(error) {
                        layer.close(index);

                        let errorMsg = '发送超过两分钟不能撤回！';
                        if (error.status === 403) {
                            errorMsg = '发送超过两分钟不能撤回！';
                        } else if (error.responseJSON && error.responseJSON.message) {
                            errorMsg = error.responseJSON.message;
                        }

                        layer.msg(errorMsg, {
                            icon: 2,
                            time: 2000,
                            shade: 0.3
                        });
                    }
                });
            });
        };

        // 标记所有未读消息为已读
        function markMessagesAsRead() {
            // 获取所有对方发送的未读消息
            const unreadMessages = [];
            $('#chatBody .message-item').each(function() {
                const $message = $(this);
                if ($message.hasClass('message-left')) { // 接收的消息
                    const messageId = $message.data('message-id');
                    const isRead = $message.find('.message-status span').text() === '已读';
                    if (!isRead) {
                        unreadMessages.push(messageId);
                    }
                }
            });

            // 调用API标记为已读
            unreadMessages.forEach(messageId => {
                $.ajax({
                    url: '/api/messages/read/' + messageId,
                    type: 'POST',
                    success: function() {
                        // 更新UI状态
                        $(`[data-message-id="${messageId}"] .message-status span`)
                            .text('已读');
                    },
                    error: function(error) {
                        console.error('标记消息为已读失败:', error);
                    }
                });
            });
        }

        // 加载消息
        function loadMessages() {
            $.ajax({
                url: '/api/messages/get?senderId=' + currentUserId + '&receiverId=' + currentReceiverId,
                type: 'GET',
                success: function(response) {
                    const chatBody = $('#chatBody');
                    chatBody.find('.empty-chat').remove();

                    // 清空现有消息
                    chatBody.find('.message-item').remove();

                    // 添加新消息
                    response.forEach(message => {
                        const isSent = message.messageObject.sender.id == currentUserId;
                        const avatarText = message.messageObject.sender.info.username.substring(0,1);

                        const messageDiv = $(`
                                <div class="message-item clearfix ${isSent ? 'message-right' : 'message-left'}"
                                     data-message-id="${message.id}">
                                    <div class="message-avatar" style="background-color:${isSent ? '#1E9FFF' : '#FF5722'}">
                                        ${avatarText}
                                    </div>
                                    <div class="message-content-wrapper">
                                        <div class="message-info">
                                            <span>${message.messageObject.sender.info.username}</span>
                                            <span>${formatTime(message.sendTime, 'yyyy-MM-dd HH:mm:ss')}</span>
                                        </div>
                                        <div class="message-content"
                                             onclick="${isSent ? 'showMessageActions(this, event)' : ''}">
                                            ${message.content ? message.content : '<span>消息已撤回</span>'}
                                            ${isSent && message.content ? `
                                            <div class="message-actions">
                                                <div class="message-action-item" onclick="recallMessage(${message.id}, event)">撤回</div>
                                            </div>
                                            ` : ''}
                                        </div>
                                        ${isSent ? `
                                        <div class="message-status">
                                            <span>${message.isRead ? '已读' : '未读'}</span>
                                        </div>
                                        ` : ''}
                                    </div>
                                </div>
                            `);

                        if (!message.content) {
                            messageDiv.find('.message-content').addClass('recalled-message');
                        }

                        chatBody.append(messageDiv);

                        // 如果是接收的消息且未读，则标记为已读
                        if (!isSent && !message.isRead) {
                            $.ajax({
                                url: '/api/messages/read/' + message.id,
                                type: 'POST',
                                success: function() {
                                    $(`[data-message-id="${message.id}"] .message-status span`)
                                        .text('已读');
                                }
                            });
                        }
                    });

                    scrollToBottom();
                },
                error: function(error) {
                    console.error('加载消息失败:', error);
                }
            });
        }

        // 发送消息
        function sendMessage() {
            const messageInput = $('#messageContent');
            const content = messageInput.val().trim();

            if (!content) {
                layer.msg('请输入消息内容', {icon: 2});
                return;
            }

            // 显示发送中指示器
            $('#sendingIndicator').show();

            // 发送到服务器
            // var messageObjectID=[[${messageObjectID}]]
            // alert(messageObjectID)
            $.ajax({
                url: '/api/messages/send',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    messageObject: {
                        id: messageObjectID
                    },
                    content: content
                }),
                success: function(data) {
                    // 隐藏发送中指示器
                    $('#sendingIndicator').hide();

                    // 清空输入框
                    messageInput.val('');

                    // 重新加载消息
                    loadMessages();
                },
                error: function() {
                    // 隐藏发送中指示器
                    $('#sendingIndicator').hide();
                    layer.msg('发送消息失败', {icon: 2});
                }
            });
        }

        // 滚动到聊天区域底部
        function scrollToBottom() {
            const chatBody = $('#chatBody');
            chatBody.scrollTop(chatBody[0].scrollHeight);
        }

        // 格式化时间
        function formatTime(dateTimeStr, format = 'yyyy-MM-dd HH:mm:ss') {
            const date = typeof dateTimeStr === 'string' ? new Date(dateTimeStr) : dateTimeStr;
            const padZero = num => num < 10 ? `0${num}` : num;

            const replacements = {
                'yyyy': date.getFullYear(),
                'MM': padZero(date.getMonth() + 1),
                'dd': padZero(date.getDate()),
                'HH': padZero(date.getHours()),
                'mm': padZero(date.getMinutes()),
                'ss': padZero(date.getSeconds())
            };

            return format.replace(/yyyy|MM|dd|HH|mm|ss/g, match => replacements[match]);
        }
    });
</script>
</body>
</html>